package com.bjpowernode.crm.web.controller;

import com.bjpowernode.crm.constants.Constants;
import com.bjpowernode.crm.pojo.User;
import com.bjpowernode.crm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class ViewController {
    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String root(@CookieValue(value = Constants.CookieNames.USER_NAME, required = false) String username,
                       @CookieValue(value = Constants.CookieNames.USER_PWD, required = false) String password,
                       HttpServletRequest request) {

        Object loginUser = request.getSession().getAttribute(Constants.LOGIN_USER);
        if(loginUser != null) {
            return "redirect:/workbench/index.html";
        }

        if (username!= null && !"".equals(username) && password!=null && !"".equals(password)) {
            String userIp = request.getRemoteAddr();
            User user = userService.getUserForAuto(username, password, userIp);
            // user为null说明不满足登录条件！
            if (user != null) {
                request.getSession().setAttribute(Constants.LOGIN_USER, user);
                return "redirect:/workbench/index.html";
            }
        }

        return "login";
    }

    /*@GetMapping("/workbench/index.html")
    public String page001() {
        return "workbench/index";
    }

    @GetMapping("/settings/index.html")
    public String page002() {
        return "settings/index";
    }*/

    // jsp的访问程序！
    @GetMapping("/**/*.html")
    public String pager(HttpServletRequest request) {
        // 动态获取访问路径
        String uri = request.getRequestURI();
        // /workbench/index.html ===> workbench/index
        return uri.substring(1, uri.lastIndexOf("."));
    }

}
